import React, { Component } from 'react';

export default class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
      user: {
        name: 'jack',
        age: 18
      }
    }

    // 绑定函数 this 指向
    this.changeCount = this.changeCount.bind(this);
  }

  changeCount() {
    // console.log(111, this)
    this.setState({
      count: this.state.count + 1
    })
  }

  changeC = () => {
    // this.setState({ count: this.state.count + 1 });
    // this.setState({ count: this.state.count + 1 });
    // this.setState({ count: this.state.count + 1 });
    this.setState((preState) => ({
      count: preState.count + 1
    }))
    this.setState((preState) => ({
      count: preState.count + 1
    }))
    this.setState((preState) => ({
      count: preState.count + 1
    }))
  }

  render() {
    return (
      <div>
        <button>-</button>
        <button disabled>{this.state.count}</button>
        {/* <button onClick={() => this.setState({
          count: this.state.count + 1
        })}>+</button> */}
        <button onClick={() => this.setState((preState) => {
          console.log(preState)
          return {
            count: preState.count + 1
          }
        })}>+</button>

        <button onClick={() => {
          // const newUser = Object.assign(this.state.user, { name: 'lily' })
          const newUser = {
            ...this.state.user,
            name: 'lily'
          }
          this.setState({
            user: newUser
          })
        }}>修改user</button>
        <p>
          <span>{this.state.user.name}</span>
          <span>{this.state.user.age}</span>
        </p>

        <button onClick={this.changeCount}>方法1：构造函数中处理 this</button>

        <button onClick={this.changeC}>探讨 state 的更新是异步还是同步</button>
      </div>
    )
  }
}